from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
# from django.template import Context, Template
import webapp2
import urllib
import json
import sys
from google.appengine.ext.webapp.template import render
import os
import cgi


MAIN_PAGE_HTML = """\
<html>
  <body>
    <form action="/compute" method="post">
      <div>row:<input type="text" name="row" value="10"></div>
      <div>col:<input type="text" name="col" value="10"></div>
      <div>y for second state:<input type="text" name="secondy" value="1"></div>
      <div>x for second state:<input type="text" name="secondx" value="0"></div>
      <div>email<input type="text" name="email" value="msnwangping@hotmail.com"></div>
      <div><input type="submit" value="submit"></div>
    </form>
  </body>
</html>
"""
    
class MyBoard:
    def __init__(self, row,col):
        self.row = row
        self.col = col
        self.board=[[0 for j in range(col)] for i in range(row)]
        
    def move(self,y,x):
        if y < 0:
            print "out of boundary"
            raise Exception
        if x < 0:
            print "out of boundary"
            raise Exception
        if y > self.row:
            print "out of boundary"
            raise Exception
        if x > self.col:
            print "out of boundary"
            raise Exception
        
        self.currentx = x
        self.currenty = y    
        self.board[y][x] = self.orientation;
        
    def cleanBoard(self):
        self.board=[[0 for j in range(self.col)] for i in range(self.row)]
        self.currentx = 0
        self.currenty = 0      
        self.orientation = 0
                
    def initGame(self,y,x,orientation):
        self.orientation = orientation
        self.move(y,x)
        while self.orientation < 0:
            self.orientation = self.orientation + 4
        self.orientation = self.orientation%4
    
        
    def doAction(self,action):
        if action == "FORWARD":
            if self.orientation == 1:
                self.move(self.currenty-1,self.currentx);
            if self.orientation == 2:
                self.move(self.currenty,self.currentx+1);
            if self.orientation == 3:
                self.move(self.currenty+1,self.currentx);
            if self.orientation == 4 or self.orientation == 0:
                self.move(self.currenty,self.currentx-1);
        if action == "LEFT":
            self.orientation = self.orientation - 1
            self.orientation = self.orientation + 4
            self.orientation = self.orientation%4
        if action == "RIGHT":
            self.orientation = self.orientation + 1
            self.orientation = self.orientation + 4
            self.orientation = self.orientation%4

    def printBoard(self):
        returnVar = []
        for row in self.board:
            temp = "";
            for element in row:
                temp = temp + str(element);
#             print temp
            returnVar.append(temp)
        print ",".join(returnVar)
        return returnVar

    def guessTheInitState(self,secondy,secondx,firstAction):
        returnVar = []
        for y in range(self.row):
            for x in range(self.col):
                for orientation in range(1,5):
                    self.cleanBoard()
                    self.initGame(y,x,orientation)
                    try:
                        self.doAction(firstAction)
                        if (self.currentx == secondx) and (self.currenty == secondy):
                            returnVar.append((y,x,orientation))
                    except Exception:
                        print "MyException encoutered",y,x
        return returnVar;
            
 



                
                

class ComputingHandler(webapp2.RequestHandler):
    def post(self):
        row = cgi.escape(self.request.get('row'))
        col = cgi.escape(self.request.get('col'))
        secondy = cgi.escape(self.request.get('secondy'))
        secondx = self.request.get('secondx')
        email = self.request.get('email')
        returnVar =self.doCompute(int(row),int(col),int(secondy),int(secondx),email)
        tmpl = os.path.join(os.path.dirname(__file__), 'xxx.html')
        self.response.out.write(render(tmpl, returnVar))
        
    def doCompute(self,row,col,secondy,secondx,email):
        errors = []
        boards = []
        results = []
        returnVar = {"errors":errors,
                     "results":results,
                     }
        
        response = urllib.urlopen("http://goserver.cloudapp.net:3000/api/spaceprobe/getdata/"+email);
#         xxx = response.read()
#         print xxx
        data = json.load(response)  
        print json.dumps(data)
        actions = data["Directions"]
        
        board = MyBoard(row,col);
        initStates = board.guessTheInitState(secondy, secondx, actions[0])
        print initStates
        
        for initState in initStates:
            board.cleanBoard()
            board.initGame(initState[0], initState[1], initState[2])
            try:
                for action in actions:
                    board.doAction(action)
                resultstr = "%s%s%s%s%s%s%s%s" % ("Init state : ", initState, ".   Destination y=" , board.currenty,", x=",board.currentx,", orientaion=",board.orientation) 
                returnVar["y"] = board.currenty
                returnVar["x"] = board.currentx
                print resultstr
                boardlines = board.printBoard()
                resultObj = {"resultstr":resultstr,"board":boardlines,}
                results.append(resultObj)
            except Exception:
                print "MyException encoutered"
        returnVar["range"] = len(returnVar)
        returnVar["initStates"] = initStates
        return returnVar
                
class Mainpage(webapp.RequestHandler):
    def get(self):
        self.response.write(MAIN_PAGE_HTML)
class SendHandler(webapp.RequestHandler):
    def post(self):
        x = self.request.get('x')
        y = self.request.get('y')
        email = self.request.get('email')
        url = "http://goserver.cloudapp.net:3000/api/spaceprobe/submitdata/"+email+"/" + x + "/" + y
        print url
        try:
            connection = urllib.urlopen(url);
            data = json.load(connection)  
            print json.dumps(data)     
            statusCode = data["StatusCode"]
            message = data["Message"]
            if int(statusCode) == 500:
                self.response.write("""<font size="3" color="red">""" + message + """</font>""")
            if int(statusCode) == 200:
                self.response.write(message);
        except Exception:
            connection = urllib.urlopen(url);
            response = connection.read()
            print response;
            self.response.write("""<font size="3" color="red">""" + response + """</font>""");
        
app = webapp2.WSGIApplication([
    ('/', Mainpage),
    ( '/compute', ComputingHandler),
    ( '/send', SendHandler),
], debug=True)
